<template>
	<div class="water-check-page">
		<div class="page-title">废水治理设施点检</div>

		<van-field v-if="isView" label="排口名称" :model-value="formData.outletName" readonly />

		<FormItemRadio
			v-if="!isView"
			label="排口类别"
			item-key="outletCategory"
			:required="true"
			v-model="formData.outletCategory"
			:dic-key="'ZQT_FSPKLX'"
			@change="onOutletCategoryChange"
		/>

		<FormItemSelect
			v-if="!isView && formData.outletCategory"
			label="排口名称"
			item-key="outletId"
			:required="true"
			v-model="formData.outletId"
			:option-list="outletOptions"
			@selected="onOutletSelected"
		/>

		<div v-if="formData.outletId" class="main-form">
			<div class="title-panel">设备维护</div>
			<FormItemRadio label="运行情况" item-key="state" :required="true" v-model="formData.state" :dic-key="'ZQT_SSZCYC'" :readonly="isView" />
			<FormItemRadio
				v-if="formData.state === '0'"
				label="异常类型"
				item-key="exceptionType"
				:required="true"
				v-model="formData.exceptionType"
				:dic-key="'ZQT_FSFQYCLX'"
			/>
			<van-field
				v-if="formData.state === '0'"
				label="异常说明"
				:required="true"
				type="textarea"
				autosize
				v-model="formData.exceptionDesc"
				placeholder="请输入"
			/>

			<FormItemDateTime
				:required="true"
				label="点检开始时间"
				item-key="beginTime"
				v-model="formData.beginTime"
				precision="hour"
				formatter="YYYY-MM-DD HH:mm"
				:readonly="isView"
				@confirm="onTimeConfirm"
			/>
			<FormItemDateTime
				:required="true"
				label="点检结束时间"
				item-key="endTime"
				v-model="formData.endTime"
				precision="hour"
				formatter="YYYY-MM-DD HH:mm"
				:readonly="isView"
				@confirm="onTimeConfirm"
			/>

			<div class="factor-form-title">
				<div class="title-panel">设备维护</div>
				<div class="near-data" v-if="!isView" @click="fetchNearData">检测数据获取</div>
			</div>

			<div class="out-water">
				<div class="out-factor-name">出水浓度</div>
				<div class="factor-info-panel">
					<div class="factor-form" v-for="item in pollutionFactor.mmol" :key="item.factorCode">
						<div class="factor-form-label"><span class="required">*</span>{{ item.factorName }}</div>
						<input
							class="input-factor"
							:readonly="isView || formData.state !== '1'"
							v-model="item.checkData"
							type="number"
							step="0.01"
							@input="onFactorInput(item)"
						/>
					</div>
				</div>
			</div>

			<div class="day-avg">
				<div class="out-factor-name">日均值</div>
				<div class="factor-info-panel">
					<div class="factor-form" v-for="item in pollutionFactor.avgDay" :key="item.factorCode">
						<div class="factor-form-label"><span class="required">*</span>{{ item.factorName }}</div>
						<input
							class="input-factor"
							:readonly="isView || formData.state !== '1'"
							v-model="item.checkData"
							type="number"
							step="0.01"
							@input="onFactorInput(item)"
						/>
					</div>
				</div>
			</div>

			<div class="flow-panel">
				<van-field label="瞬时流量(升/秒)" :required="true" type="number" v-model="formData.instantData" :readonly="isView" placeholder="请输入" />
				<van-field label="累计流量(吨)" :required="true" type="number" v-model="formData.totalData" :readonly="isView" placeholder="请输入" />
				<van-field label="日累计流量(吨)" :required="true" type="number" v-model="formData.totalDataDay" :readonly="isView" placeholder="请输入" />
			</div>

			<FormFileUpload v-model="formData.fileData" :readonly="isView" :business-id="formData.id" big-type="ZQT_SSDJFJ_FS" small-type="FJ" />
		</div>

		<div style="margin: 16px" v-if="!isView">
			<van-button block type="primary" @click="onSave">提交</van-button>
		</div>
	</div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import dayjs from 'dayjs'
import { showToast, showConfirmDialog } from 'vant'
import { normalizeDateTime, isEndAfterOrEqual } from '@/utils/timeUtils'
import { useRoute, useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { getLocation } from '@/api'
import {
	getWaterDetail,
	getOutletsWater,
	getLastRealMonitorDataWater,
	getLastDayMonitorDataWater,
	getNearDataWater,
	addWaterCheck,
} from '@/api/facilityWater'
import FormItemRadio from '@/components/form-item-radio'
import FormFileUpload from '@/components/form-file-upload'
import FormItemSelect from '@/components/form-item-select'
import FormItemDateTime from '@/components/form-item-time/FormItemDateTime.vue'

export default {
	name: 'WaterFacilityCheck',
	components: { FormItemRadio, FormFileUpload, FormItemSelect, FormItemDateTime },
	setup() {
		const route = useRoute()
		const router = useRouter()
		const userStore = useUserStore()

		const isView = ref(route.query.isView === 'true')
		const outletOptions = ref([])
		const pollutionFactor = reactive({ mmol: [], avgDay: [] })

		const formData = reactive({
			id: generateId(),
			pollutionSourceId: '',
			outletCategory: '',
			outletId: '',
			outletName: '',
			state: '',
			exceptionType: '',
			exceptionDesc: '',
			beginTime: dayjs().format('YYYY-MM-DD HH:mm:00'),
			endTime: dayjs().add(1, 'hour').format('YYYY-MM-DD HH:mm:00'),
			instantData: '',
			totalData: '',
			totalDataDay: '',
			longitude: '',
			latitude: '',
			facilityCheckFactorWateList: [],
			fileData: [],
		})

		function generateId() {
			return 'ID' + Math.random().toString(16).slice(2)
		}

		const init = async () => {
			const user = await userStore.ensureLogin()
			formData.pollutionSourceId = user?.omDepts?.id || ''
			if (isView.value && route.query.id) {
				loadDetail(route.query.id)
			} else {
				try {
					const loc = await getLocation()
					formData.longitude = loc.longitude
					formData.latitude = loc.latitude
				} catch (e) {}
			}
		}

		const loadDetail = async (id) => {
			const res = await getWaterDetail(id)
			if (res.data) {
				Object.assign(formData, res.data)
				pollutionFactor.mmol = res.data.facilityCheckFactorWateList.filter((o) => o.checkType === 'CSND')
				pollutionFactor.avgDay = res.data.facilityCheckFactorWateList.filter((o) => o.checkType === 'ZXYQRJZ')
				await loadOutlets(formData.pollutionSourceId)
			} else {
				showToast('未查询到数据')
			}
		}

		const loadOutlets = async (pollutionSourceId) => {
			if (!pollutionSourceId) return
			const res = await getOutletsWater(pollutionSourceId, formData.outletCategory)
			if (Array.isArray(res.data)) {
				outletOptions.value = res.data.map((d) => ({ text: d.outletName, value: d.id, detail: d }))
			} else {
				outletOptions.value = []
			}
		}

		const onOutletCategoryChange = async ({ outletCategory }) => {
			formData.outletCategory = outletCategory
			formData.outletId = ''
			formData.outletName = ''
			outletOptions.value = []
			pollutionFactor.mmol = []
			pollutionFactor.avgDay = []
			await loadOutlets(formData.pollutionSourceId)
		}

		const onOutletSelected = async (payload) => {
			const val = payload.data.value
			const opt = outletOptions.value.find((o) => o.value === val)
			if (!opt) return
			formData.outletId = opt.value
			formData.outletName = opt.text
			if (opt.detail?.pollutionFactorCode) {
				const codes = opt.detail.pollutionFactorCode.split(',')
				const names = (opt.detail.pollutionFactorName || '').split(',')
				pollutionFactor.mmol = codes.map((c, i) => ({
					checkType: 'CSND',
					factorCode: c,
					factorName: names[i] || c,
					checkData: '',
					checkId: formData.id,
				}))
				pollutionFactor.avgDay = codes.map((c, i) => ({
					checkType: 'ZXYQRJZ',
					factorCode: c,
					factorName: names[i] || c,
					checkData: '',
					checkId: formData.id,
				}))
				const dayRes = await getLastDayMonitorDataWater(opt.detail.outletCode, codes)
				if (Array.isArray(dayRes.data) && dayRes.data.length > 0) {
					fillArrayData(dayRes.data, 'igCode', 'monitorAvgValue', pollutionFactor.avgDay, 'factorCode', 'checkData')
				}
				const realRes = await getLastRealMonitorDataWater(opt.detail.outletCode, codes)
				if (Array.isArray(realRes.data) && realRes.data.length > 0) {
					fillArrayData(realRes.data, 'igCode', 'monitorAvgValue', pollutionFactor.mmol, 'factorCode', 'checkData')
				}
				formData.facilityCheckFactorWateList = [...pollutionFactor.mmol, ...pollutionFactor.avgDay]
			}
		}

		const fillArrayData = (from, formField, formValue, target, targetField, targetValueField) => {
			target.forEach((m) => {
				from.forEach((r) => {
					if (r[formField] === m[targetField]) m[targetValueField] = r[formValue]
				})
			})
		}

		const fetchNearData = async () => {
			const beginTime = dayjs().add(-10, 'day').format('YYYY-MM-DD HH:mm:ss')
			const res = await getNearDataWater(beginTime, formData.pollutionSourceId)
			if (!res.data) {
				showToast('最近10天内无上报记录')
				return
			}
			try {
				await showConfirmDialog({ title: '提示', message: `获取最近[${beginTime}]上报数据，是否填充?` })
				const mmol = res.data.facilityCheckFactorWateList.filter((o) => o.checkType === 'CSND')
				const avgDay = res.data.facilityCheckFactorWateList.filter((o) => o.checkType === 'ZXYQRJZ')
				fillArrayData(mmol, 'factorCode', 'checkData', pollutionFactor.mmol, 'factorCode', 'checkData')
				fillArrayData(avgDay, 'factorCode', 'checkData', pollutionFactor.avgDay, 'factorCode', 'checkData')
				formData.facilityCheckFactorWateList = [...mmol, ...avgDay]
			} catch (e) {}
		}

		const onFactorInput = () => {
			formData.facilityCheckFactorWateList = [...pollutionFactor.mmol, ...pollutionFactor.avgDay]
		}

		const validate = () => {
			if (!formData.outletCategory) return showToast('请选择排扣类别'), false
			if (!formData.outletName) return showToast('请选择排扣'), false
			if (!formData.state) return showToast('请选择运行情况'), false
			if (formData.state === '0') {
				if (!formData.exceptionType) return showToast('请选择异常类型'), false
				if (!formData.exceptionDesc) return showToast('请输入异常说明'), false
			}
			if (formData.state === '1' && formData.facilityCheckFactorWateList.some((item) => !item.checkData && item.checkData !== 0)) {
				return showToast('设备数据存在必填项为空，请检查'), false
			}
			if (!formData.instantData) return showToast('请输入瞬时流量'), false
			if (!formData.totalData) return showToast('请输入累计流量'), false
			if (!formData.totalDataDay) return showToast('请输入日累计流量'), false
			if (!formData.fileData || formData.fileData.length === 0) return showToast('请上传附件'), false
			return true
		}

		const onTimeConfirm = (obj) => {
			Object.assign(formData, obj)
		}

		const onSave = async () => {
			if (!validate()) return
			formData.beginTime = normalizeDateTime(formData.beginTime)
			formData.endTime = normalizeDateTime(formData.endTime)
			if (!isEndAfterOrEqual(formData.beginTime, formData.endTime)) {
				return showToast('结束时间不能早于开始时间')
			}
			const res = await addWaterCheck(formData)
			if (res.code === '0') {
				showToast('提交成功')
				setTimeout(() => router.back(), 1200)
			}
		}

		onMounted(() => init())

		return {
			isView,
			formData,
			pollutionFactor,
			outletOptions,
			onOutletCategoryChange,
			onOutletSelected,
			fetchNearData,
			onSave,
			onFactorInput,
			onTimeConfirm,
		}
	},
}
</script>

<style lang="less" scoped>
.water-check-page {
	padding-bottom: 40px;
}
.page-title {
	font-size: 18px;
	font-weight: 600;
	padding: 16px;
}
.title-panel {
	font-weight: 600;
	margin: 8px 0 8px 8px;
}
.factor-form-title {
	display: flex;
	justify-content: space-between;
}
.out-factor-name {
	font-weight: 600;
	font-size: 12px;
	margin: 8px 0 8px 8px;
}
.factor-info-panel {
	display: flex;
	flex-wrap: wrap;
}
.required {
	color: #f93333;
}
.factor-form {
	width: 80px;
	margin: 2px 5px;
}
.factor-form-label {
	color: #969799;
	font-size: 12px;
	margin: 2px;
	text-align: center;
	width: 80px;
	white-space: nowrap;
	overflow: hidden;
	text-overflow: ellipsis;
}
.input-factor {
	border: 1px solid #d5d5d5;
	padding: 2px 5px;
	text-align: center;
	font-size: 12px;
	color: #969799;
	width: 100%;
}
.near-data {
	border: 1px solid #0099ff;
	font-size: 12px;
	color: #0099ff;
	padding: 4px;
	margin: 8px;
	cursor: pointer;
}
.day-avg {
	background-color: #fff;
	padding: 2px 0;
}
.flow-panel :deep(.van-field) {
	margin-top: 4px;
}
</style>